import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qilo/core/constants/app_colors.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import '../../../core/models/teach.dart';
import '../../../core/widgets/transgression_reporting_portal.dart';
import '../../../core/constants/teach_video.dart';

class MediaPresentationScreen extends StatefulWidget {
  final Teach teachContent;

  const MediaPresentationScreen({super.key, required this.teachContent});

  @override
  State<MediaPresentationScreen> createState() =>
      _MediaPresentationScreenState();
}

class _MediaPresentationScreenState extends State<MediaPresentationScreen> {
  late VideoPlayerController _videoPlayerController;
  ChewieController? _chewieController;
  bool _isVideoInitialized = false;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
  }

  @override
  void dispose() {
    _chewieController?.dispose();
    _videoPlayerController.dispose();
    super.dispose();
  }

  /// 初始化视频播放器
  Future<void> _initializeVideoPlayer() async {
    try {
      _videoPlayerController = VideoPlayerController.networkUrl(
        Uri.parse(widget.teachContent.videoUrl),
      );

      await _videoPlayerController.initialize();

      _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: false,
        looping: false,
        aspectRatio: 375 / 241,
        allowFullScreen: true,
        allowMuting: true,
        showControls: true,
        materialProgressColors: ChewieProgressColors(
          playedColor: AppColors.iconColor,
          handleColor: AppColors.iconColor,
          backgroundColor: Colors.grey.withValues(alpha: 0.3),
          bufferedColor: AppColors.iconColor.withValues(alpha: 0.3),
        ),
        placeholder: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(widget.teachContent.coverUrl),
              fit: BoxFit.cover,
            ),
          ),
        ),
      );

      setState(() {
        _isVideoInitialized = true;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      debugPrint('Error initializing video: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/video-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: Stack(
            children: [
              Center(child: _buildContentArea()),
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: _buildNavigationHeader(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildNavigationHeader() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _buildActionButton(
            icon: Icons.arrow_back_ios,
            onPressed: () => Navigator.pop(context),
          ),
          _buildActionButton(
            icon: MyIcons.iconReport,
            onPressed: _handleReportAction,
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButton({
    required IconData icon,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(
          color: AppColors.iconColor,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, color: AppColors.white, size: 22.sp),
      ),
    );
  }

  /// 构建内容播放区域
  Widget _buildContentArea() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 0.w),
      child: AspectRatio(
        aspectRatio: 375 / 241,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(0.r),
          ),
          child:
              _isLoading
                  ? _buildLoadingWidget()
                  : _isVideoInitialized && _chewieController != null
                  ? Chewie(controller: _chewieController!)
                  : _buildErrorWidget(),
        ),
      ),
    );
  }

  /// 构建加载中组件
  Widget _buildLoadingWidget() {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(widget.teachContent.coverUrl),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          // 渐变遮罩
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.transparent,
                  Colors.black.withValues(alpha: 0.4),
                ],
              ),
            ),
          ),
          // 加载指示器
          Center(
            child: Container(
              width: 80.w,
              height: 80.w,
              decoration: BoxDecoration(
                color: AppColors.white.withValues(alpha: 0.9),
                borderRadius: BorderRadius.circular(40.r),
              ),
              child: const Center(
                child: CircularProgressIndicator(color: AppColors.iconColor),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget() {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(widget.teachContent.coverUrl),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          // 渐变遮罩
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.transparent,
                  Colors.black.withValues(alpha: 0.4),
                ],
              ),
            ),
          ),
          // 错误提示
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, color: AppColors.white, size: 48.sp),
                SizedBox(height: 16.h),
                Text(
                  'Video loading failed',
                  style: TextStyle(
                    color: AppColors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 16.h),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _isLoading = true;
                    });
                    _initializeVideoPlayer();
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 24.w,
                      vertical: 12.h,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.iconColor,
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child: Text(
                      'Retry',
                      style: TextStyle(
                        color: AppColors.white,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 处理举报操作
  void _handleReportAction() {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: widget.teachContent.id,
      targetType: 'video_content',
      onReportSubmitted: (transgression) {
        // 举报成功后删除视频并返回上一页
        _deleteVideoAndGoBack();
      },
    );
  }

  /// 删除视频并返回上一页
  void _deleteVideoAndGoBack() {
    // 从 TeachVideo.allTeach 列表中删除当前视频
    TeachVideo.allTeach.removeWhere(
      (teach) => teach.id == widget.teachContent.id,
    );

    // 返回上一页，并传递刷新标志
    Navigator.of(context).pop(true); // 传递 true 表示需要刷新列表
  }
}
